package com.hao;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class PubSub {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置参数
        factory.setHost("8.130.120.148");
        factory.setPort(5672);
        factory.setVirtualHost("/kaiyuan");
        factory.setUsername("shihao");
        factory.setPassword("shihao");
        // 3.创建连接Connection
        Connection connection = factory.newConnection();
        // 4.创建Channel
        Channel channel = connection.createChannel();
        // 5.创建交换机
        /**
         * exchangeDeclare(String exchange,
         *         BuiltinExchangeType type,
         *         boolean durable,
         *         boolean autoDelete,
         *         boolean internal,
         *         Map<String, Object> arguments)
         * 1. exchange 交换机名称
         * 2. type: 四种类型
         * DIRECT("direct"), 定向
         * FANOUT("fanout"), 扇形（广播）：发送消息到每一个和它绑定的队列
         * TOPIC("topic"), 通配符方式
         * HEADERS("headers"); 参数匹配
         * 3.durable: 是否持久化
         * 4.autoDelete: 是否自动删除
         * 5.internal: 内部使用，一般为false
         * 6.arguments：参数
         */
        String exchangeName= "test_fanout";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false    ,null);
        // 6.创建队列
        String queue1Name="test_fanout_queue1";
        String queue2Name="test_fanout_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        // 7.绑定队列和交换机
        /**
         * 如果交换机类型为：fanout，则 routingKey设置为 ""
         */
        channel.queueBind(queue1Name,exchangeName,"");
        channel.queueBind(queue2Name,exchangeName,"");
        // 8.发送消息
        String body = "Hello,PubSub";
        channel.basicPublish(exchangeName,"",null,body.getBytes());
        // 9.释放资源
        channel.close();
        connection.close();


    }
}
